package com.linjj.seckill.validator;

import com.alibaba.druid.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

public class IsPhoneValidator implements ConstraintValidator<IsPhone, String> {
    private boolean require;
    @Override
    public void initialize(IsPhone isPhone) {
        this.require = isPhone.require();
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if(require==true){
            return isPhone(s);
        }else{
            if(StringUtils.isEmpty(s)){
                return true;
            }else{
                return isPhone(s);
            }
        }
    }

    private boolean isPhone(String phone){
        if(StringUtils.isEmpty(phone)){
            return false;
        }
        Pattern phonePattern = Pattern.compile("1[3-9]\\d{9}");
        return phonePattern.matcher(phone).matches();
    }
}
